<template>
	<view class="apply">
		<u-navbar title="财务申请" back-icon-color="#fff" title-color="#fff" :background="background">
			<view class="navbar-right" slot="right">
				<view class="dot-box right-item" @click="historyList">
					<u-image shape="square" ref="uImage" width="40" height="40" src="../../static/icon/history-icon.png" mode="aspectFill">
					</u-image>
				</view>
			</view>
		</u-navbar>
		
		<view class="apply-contnet">
			<!-- 申请人 -->
			<view class="bg-white row-between apply-item mt20">
				<view>
					<text class="required-color">*</text>
					<text class="ml10 bold">申请人</text>
				</view>
				<view>
					{{userinfo.realname}}
				</view>
			</view>
			
			<!-- 申请部门 -->
			<view class="bg-white row-between mt20 apply-item">
				<view>
					<text class="required-color">*</text>
					<text class="ml10 bold">申请部门</text>
				</view>
				<view>
					{{userinfo.bumen}}
				</view>
			</view>
			
			<!-- 申请类型 -->
			<view class="bg-white row-between mt20 apply-item">
				<view>
					<text class="required-color">*</text>
					<text class="ml10 bold">
						申请类型
					</text>
				</view>
				<view>
					<u-input :border="border" type="select" :select-open="typeShow" v-model="apply_type" placeholder="请选择申请类型" @click="typeShow = true"></u-input>
				</view>
			</view>
			
			<!-- 配送日期 -->
			<view class="bg-white row-between mt20 apply-item" @click="showChange"	>
				<view>
					<text class="required-color">*</text>
					<text class="ml10 bold">
						配送日期
					</text>
				</view>
				<view >
					{{deliver_date}}
				</view>
			</view>
			
			<!-- 日期选择 -->
			<u-calendar v-model="dateShow" ref="calendar" @change="dateChange" :mode="dateMode"
				 :active-bg-color="activeBgColor" :btn-type="btnType" :min-date="minDate" :max-date="maxDate"
			>
			</u-calendar>
			
			<!-- 申请金额 -->
			<view class="bg-white row-between mt20 apply-item">
				<view>
					<text class="required-color">*</text>
					<text class="ml10 bold">
						<block v-if="source == ''">申请金额</block>
						<block v-else>实际金额</block>
					</text>
				</view>
				<view>
					<u-input :inputAlign="inputAlign" v-model="amount" :placeholder="source == '' ? '请输入申请金额' : '请输入实际金额'" :type="type" :border="border" />
				</view>
			</view>
			
			<!-- 申请说明 -->
			<view class="bg-white mt20 apply-item">
				<view >
					<text class="required-color">*</text>
					<text class="ml10 bold">申请说明</text>
				</view>
				<view>
					<u-input v-model="content" :height="textareaHeight" placeholder="请详细描述申请" :type="textareaType" :border="border" :auto-height="autoHeight" />
				</view>
			</view>
			
			<!-- 申请详单 -->
			<view class="bg-white mt20 apply-item">
				<view>
					<text class="required-color">*</text>
					<text class="ml10 bold">申请详单</text>
				</view>
				
				<view class="mt20 review-list">
					<view class="row-between detail-item title">
						<view class="detail-item-child-one">
							
						</view>
						<view class="detail-item-child">
							物品名称
						</view>
						<view class="detail-item-child">
							商品材质
						</view>
						<view class="detail-item-child">
							规格型号
						</view>
						<view class="detail-item-child">
							单位
						</view>
						<view class="detail-item-child">
							数量
						</view>
						<view class="detail-item-child">
							预估单价
						</view>
						<view class="detail-item-child">
							预估总价
						</view>
					</view>
					<view class="row-between detail-item content" v-for="(item, index) in detailArr" v-key="index">
						<view class="detail-item-child-one order-number">
							{{index + 1}}
						</view>
						<view class="row detail-item-child">
							<text class="line1">
								{{item.name}}
							</text>
						</view>
						<view class="detail-item-child line1">
							<text class="line1">
								{{item.material}}
							</text>
						</view>
						<view class="detail-item-child line1">
							<text class="line1">
								{{item.specifications}}
							</text>
						</view>
						<view class="detail-item-child line1">
							<text class="line1">
								{{item.unit}}
							</text>
						</view>
						<view class="detail-item-child">
							<text class="line1">
								{{item.number}}
							</text>
						</view>
						<view class="detail-item-child">
							<text class="line1">
								{{item.unit_price}}
							</text>
						</view>
						<view class="detail-item-child">
							<text class="line1">
								{{item.total_price}}
							</text>
						</view>
					</view>
				</view>
				
				<view class="add row-center u-text-center" @click="showDetail = true" v-if="source == ''">
					<u-icon name="plus-circle" color="#2C48F2" size="32"></u-icon>
					<text class="ml10">添加</text>
				</view>
			</view>
			
			
			<!-- 图片上传 -->
			<view class="bg-white mt20 apply-item">
				<view class="row-between">
					<view class="bold">
						图片
					</view>
					<view>
						<u-upload ref="uUpload"
							:action="baseurl+action"
							:before-remove="beforeRemove" 
							:custom-btn="true" 
							:show-upload-list="showUploadList" 
							:auto-upload="true" 
							:deletable="deletable" 
							:max-count="maxCount" 
							@on-list-change="onListChange"
							v-on:on-success="diploma_imageResult"
							:file-list="fileList"
						>
							<view slot="addBtn" class="slot-btn" hover-class="slot-btn__hover" hover-stay-time="150">
								<u-image width="46rpx" height="42rpx" src="../../static/icon/add-image.png"></u-image>
							</view>
						</u-upload>
					</view>
				</view>
				
				<view class="pre-box row mt20" v-if="!showUploadList">
					<view class="pre-item" v-for="(item, index) in applyfileList" :key="index">
						<image class="pre-item-image" :src="item.url" mode="aspectFill" @click="imgListPreview(index)"></image>
						<view class="u-delete-icon" @tap.stop="deleteItem(index)">
							<u-icon name="close" size="20" color="#ffffff"></u-icon>
						</view>
						<u-line-progress v-if="item.progress > 0 && !item.error" :show-percent="false" height="16" class="u-progress"
						 :percent="item.progress"></u-line-progress>
					</view>
				</view>
			</view>
			
			<!-- 流程审批人 -->
			<view class="bg-white mt20 apply-item">
				<view class="bold">流程</view>
				<view class="">
					<view class="add-leader-list row" v-for="(item, index) in approverArr" v-key="index">
						<view class="leader-circle"></view>
						<view class="row-between list-content">
							<view class="">
								<view class="">
									审批人
								</view>
								<view class="muted xxs">
									{{item.realname == '' ? '请选择审批人' : item.realname}}
								</view>
							</view>
							<view class="row-center" @click="clickAuditShow" :data-index="index">
								<u-image width="50rpx" height="50rpx" src="../../static/icon/add_audit_leader.png"></u-image>
							</view>
						</view>
					</view>
					
					<view class="add row-center u-text-center" @click="addApprover">
						<u-icon name="plus-circle" color="#2C48F2" size="32"></u-icon>
						<text class="ml10">添加</text>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 提交按钮 -->
		<view class="submit-btn white" @click="verificationData">
			<view class="submit-btn-content row-center">
				提交
			</view>
		</view>
		
		<!-- 申请类型选择器 -->
		<u-select mode="single-column" :list="typeList" v-model="typeShow" @confirm="typeConfirm"></u-select>
		<!-- 审批人选择器 -->
		<u-select v-model="auditShow" mode="mutil-column-auto" :list="leaderList" @confirm="auditConfirm"></u-select>
		
		<u-popup v-model="showDetail" @open="openDetail" mode="bottom" border-radius="20" height="75%" :closeable="true" close-icon-size="32">
			<view class="detail-popup">
				<u-form :model="form" :rules="rules" ref="uForm" :errorType="errorType">
					<u-form-item label="物品名称" :label-position="labelPosition" prop="name">
						<u-input v-model="form.name" type="text" />
					</u-form-item>
					<u-form-item label="商品材质" :label-position="labelPosition" prop="material">
						<u-input v-model="form.material" type="text" />
					</u-form-item>
					<u-form-item label="规格型号" :label-position="labelPosition" prop="specifications">
						<u-input v-model="form.specifications" type="text" />
					</u-form-item>
					<u-form-item label="单位" :label-position="labelPosition" prop="unit">
						<u-input v-model="form.unit" type="text" />
					</u-form-item>
					<u-form-item label="数量" :label-position="labelPosition" prop="number">
						<u-input v-model="form.number" type="text" />
					</u-form-item>
					<u-form-item label="预估单价" :label-position="labelPosition" prop="unit_price">
						<u-input v-model="form.unit_price" type="text" />
					</u-form-item>
					<u-form-item label="预估总价" :label-position="labelPosition" prop="total_price">
						<u-input v-model="form.total_price" type="text" />
					</u-form-item>
				</u-form>
				<view class="submit-btn white" @click="saveDetailData">
					<view class="submit-btn-content row-center">
						保存
					</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				background: {
					backgroundColor: '#2165F7',
				},
				
				type: 'text',
				textareaType: 'textarea',
				textareaHeight: 100,
				autoHeight: true,
				border: false,
				inputAlign: 'right',
				showDetail: false, // 展示
				
				userinfo: {},
				// 申请详单中的信息
				labelPosition: 'top',
				errorType: ['message'],
				form: {
					name: '',
					material: '',
					specifications: '',
					unit: '',
					number: '',
					unit_price: '',
					total_price: '',
				},
				rules: {
					name: [
						{
							required: true,
							message: '请输入物品名称',
							trigger: 'blur' ,
						}
					],
					material: [
						{
							required: true,
							message: '请输入商品材质',
							trigger: 'blur' ,
						}
					],
					specifications: [
						{
							required: true,
							message: '请输入规格型号',
							trigger: 'blur' ,
						}
					],
					unit: [
						{
							required: true,
							message: '请输入单位',
							trigger: 'blur' ,
						}
					],
					number: [
						{
							required: true,
							message: '请输入数量',
							trigger: 'blur' ,
						}
					],
					unit_price: [
						{
							required: true,
							message: '请输入预估单价',
							trigger: 'blur' ,
						},
						{
							// 此为同步验证，可以直接返回true或者false，如果是异步验证，稍微不同，见下方说明
							validator: (rule, value, callback) => {
								// 调用uView自带的js验证规则，详见：https://v1.uviewui.com/js/test.html
								return this.$u.test.amount(value);
							},
							message: '预估单价金额有误',
							// 触发器可以同时用blur和change，二者之间用英文逗号隔开
							trigger: ['change','blur'],
						},
					],
					total_price: [
						{
							required: true,
							message: '请输入预估总价',
							trigger: 'blur' ,
						},
						{
							// 此为同步验证，可以直接返回true或者false，如果是异步验证，稍微不同，见下方说明
							validator: (rule, value, callback) => {
								// 调用uView自带的js验证规则，详见：https://v1.uviewui.com/js/test.html
								return this.$u.test.amount(value);
							},
							message: '预估总价金额有误',
							// 触发器可以同时用blur和change，二者之间用英文逗号隔开
							trigger: ['change','blur'],
						},
					],
				},
				
				// 上传
				baseurl:"",
				action: '/api/member/userupload',
				deletable: true,
				showUploadList: false,
				maxCount: 99,
				fileList: [],
				applyfileList: [],
				
				id: '',
				source: '',
				auditShow: false,
				primaryDefaultSelector: [0, 0],
				leaderList: [],
				typeList: [],
				typeShow: false,
				
				dateShow: false,
				dateMode: 'date',
				activeBgColor: '#2165F7',
				btnType: 'primary',
				minDate: '',
				maxDate: '',
				
				apply_type: '',
				apply_type_id: '',
				deliver_date: '',
				amount: '',
				content: '',
				imgArr: [],
				audit_uids: [], // 审核人提交到接口的数组
				detailArr: [],
				
				// 审核人数组，用于循环显示
				approverArr: [{
					id: '',
					realname: '',
				}],
				// 记录选择到了那个下标
				click_index: '',
			}
		},
		onLoad(optinos) {
			let _this = this;
			_this.baseurl = _this.$u.http.config.baseUrl
			_this.userinfo = uni.getStorageSync('userinfo');
			
			let currentDate = new Date(),
			year = currentDate.getFullYear(),
			month = currentDate.getMonth() + 1,
			day = currentDate.getDate();
			
			_this.minDate = year + '-' + month + '-' + day; //获取当前时间
			_this.maxDate = _this.nextMonthLastDay(); // 获取下月最后一天
			
			// 判断来自哪个按钮，review来自最终审核
			if(optinos.source != undefined) {
				_this.source = optinos.source;
			}
			
			if(optinos.id != undefined) {
				_this.id = optinos.id;
				_this.getDetailFun();
			}
			// 获取审核人列表
			_this.getLeaderFun();
		},
		methods: {
			showChange() {
				this.dateShow = !this.dateShow;
			},
			dateChange(e) {
				this.deliver_date = e.result;
			},
			getDetailFun: function() {
				let _this = this;
				let post_params = {
					review_id: this.id,
				};
				this.$u.post('/api/review/userReviewDetail', post_params).then(res => {
					_this.amount = res.review_info.amount;
					_this.content = res.review_info.content;
					
					res.review_info.images_arr.forEach(function(item, index) {
						let _tmp = {
							url: res.review_info.images_domain + item
						}
						_this.fileList.push(_tmp);
					})
					
					_this.imgArr = res.review_info.images_arr;
					
					// 回填申请单详情信息
					_this.detailArr = res.review_item;
					
					// 回填审核人信息
					let new_approverArr = [];
					res.review_ren_list.forEach(function(item, index) {
						let _tmp = {};
						_tmp.id = item.user_id;
						_tmp.realname = item.realname;
						new_approverArr.push(_tmp);
					})
					_this.approverArr = new_approverArr;
				});
			},
			// 选择申请类型回调
			typeConfirm(e) {
				this.apply_type = '';
				e.map((val, index) => {
					this.apply_type += this.apply_type == '' ? val.label : '-' + val.label;
					this.apply_type_id = val.value;
				})
			},
			// 获取审核人
			getLeaderFun() {
				this.$u.post('/api/review/shenpiRenList', {}).then(res => {
					this.leaderList = res.bumenlist;
					
					let _typeObj = res.typeList;
					let new_type = [];
					for(let t in _typeObj) {
						let _tmp = {};
						_tmp.value = t;
						_tmp.label = _typeObj[t];
						new_type.push(_tmp);
					}
					this.typeList = new_type;
				});
			},
			openDetail() {
				let _this = this;
				_this.$refs.uForm.setRules(_this.rules)
			},
			saveDetailData: function() {
				let _this = this;
				
				_this.$refs.uForm.validate(valid => {
					if (valid) {
						let _detailArr = _this.detailArr;
						let _form = _this.form;
						let _tmp = [];
						for(let f in _form) {
							_tmp[f] = _form[f]
						}
						
						_detailArr.push(_tmp);
						_this.detailArr = _detailArr;
						_this.showDetail = false;
						
						_this.$nextTick(function(){
							_this.$refs.uForm.resetFields(_this.rules)
						})
						
					} else {
						console.log('验证失败');
					}
				});
			},
			verificationData: function() {
				let _this = this;
				let {
					amount,
					content,
					audit_uids,
					apply_type,
					deliver_date
				} = _this;
				
				if(!_this.isNull(apply_type)) {
					uni.showToast({
						title: '申请类型必选',
						icon: "none"
					})
					return false;
				}
				
				if(!_this.isNull(deliver_date)) {
					uni.showToast({
						title: '请选择配送日期',
						icon: "none"
					})
					return false;
				}
				
				if(!_this.isNull(amount)) {
					uni.showToast({
						title: '申请金额必填',
						icon: "none"
					})
					return false;
				}
				
				if (!_this.isNumber(amount)) {
					uni.showToast({
						title: '请输入正确的金额',
						icon: "none"
					})
					return;
				}
				
				if(!_this.isNull(content)) {
					uni.showToast({
						title: '申请内容必填',
						icon: "none"
					})
					return false;
				}
				
				let _audit_uids = [];
				let _approverArr = _this.approverArr;
				
				_approverArr.forEach(function(item,index) {
					_audit_uids.push(item.id)
				})
				
				if(_audit_uids.indexOf(_this.userinfo.id) > -1) {
					uni.showToast({
						title: '审核人不能包含自己，请重新选择',
						icon: "none"
					})
					return false;
				}
				
				_this.audit_uids = _audit_uids;
				
				_this.submintFun();
			},
			// 提交
			submintFun() {
				let _this = this;
				let _images = _this.imgArr.toString();
				let _detailArr = _this.detailArr;
				let new_detail_arr = [];
				_detailArr.forEach(function(item, index) {
					let _tmp = {};
					_tmp.name = item.name;
					_tmp.material = item.material;
					_tmp.specifications = item.specifications;
					_tmp.unit = item.unit;
					_tmp.number = item.number;
					_tmp.unit_price = item.unit_price;
					_tmp.total_price = item.total_price;
					new_detail_arr.push(_tmp)
				})
				let post_params = {
					amount: _this.amount,
					content: _this.content,
					images: _images,
					audit_uids: _this.audit_uids,
					item: new_detail_arr,
					type: _this.apply_type_id,
					deliver_date: _this.deliver_date
				};
				
				if(_this.source == 'review') {
					post_params.pid = _this.id;
				}
				this.$u.post('/api/review/addreview', post_params).then(res => {
					uni.redirectTo({
						url: '/pages/finance/applyList'
					})
				});
			},
			// 历史记录
			historyList: function() {
				uni.navigateTo({
					url: '/pages/finance/applyList'
				})
			},
			
			//上传申请图片
			diploma_imageResult(e){
				let _this = this;
				if(e.code == 1){
					_this.imgArr.push(e.data.url)
				}
			},
			onListChange(lists) {
				this.applyfileList = lists;
			},
			beforeRemove(index, lists) {
				return true;
			},
			//删除图片
			deleteItem(index) {
				let _this = this;
				uni.showModal({
					title: '提示',
					content: '您确定删除此项吗？',
					cancelText: "取消", // 取消按钮的文字  
					confirmText: "确定", // 确认按钮文字  
					showCancel: true, // 是否显示取消按钮，默认为 true
					success: (res) => {
						if(res.confirm) {  
							_this.$refs.uUpload.remove(index);
							_this.imgArr.splice(index,1)
						} else {  
							console.log('else', res)
						}  
					} 
				})
			},
			
			//预览图片
			imgListPreview(index){
				let _this = this;
				let urlList = _this.imgArr;
				let newUrlList = [];
				urlList.forEach(function(item, index){
					newUrlList.push(_this.baseurl + item);
				});
				
				uni.previewImage({
					urls: newUrlList,
					current: index
				})
			},
			// 增加审核人
			addApprover() {
				let _this = this;
				let _tmp = {};
				_tmp.id = "";
				_tmp.realname = "";
				
				_this.approverArr.push(_tmp);
			},
			// 打开审核人选择
			clickAuditShow(e) {
				let _this = this;
				let _index = e.currentTarget.dataset.index;
				_this.click_index = _index;
				_this.auditShow = true;
			},
			// 选择审核人
			auditConfirm(e) {
				let choose_obj = e[1];
				let _click_index = this.click_index;
				if(choose_obj.label != null && choose_obj.value != null) {
					this.approverArr[_click_index].id = choose_obj.value;
					this.approverArr[_click_index].realname = choose_obj.label;
				}
			},
			
			
			isNull(value) {
				if(value == '' || value == 0 || value == undefined) {
					return false;
				}
				return true;
			},
			isNumber:function(val){
			    var regPos = /^\d+(\.\d+)?$/; //非负浮点数
			    var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
			    if(regPos.test(val) || regNeg.test(val)){
			        return true;
			    }else{
			        return false;
			    }
			},
			// 获取下月的最后一天
			nextMonthLastDay: function() {
				let time = new Date();
				let year = time.getFullYear();
				let month = time.getMonth() + 2;
			 
				if (month > 12) {
					month = month - 12;
					year = year + 1;
				}
				let day = this.nextMonthDay(year, month);
				return year + '-' + month + '-' + day;
			},
			// 判断每月多少天
			nextMonthDay: function(year, month) {
				let day31 = [1, 3, 5, 7, 8, 10, 12];
				let day30 = [4, 6, 9, 11];
			 
				if (day31.indexOf(month) > -1) {
					return 31;
				} else if (day30.indexOf(month) > -1) {
					return 30;
				} else {
					if (this.isLeapYear(year)) {
						return 29;
					} else {
						return 28;
					}
				}
			},
			//判断是否为闰年
			isLeapYear: function(year) {
				return (year % 4 == 0) && (year % 100 != 0 || year % 400 == 0);
			},
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #F6F6F6;
	}
	.apply {
		.navbar-right {
			margin-right: 24rpx;
			display: flex;
		}
		
		.right-item {
			margin: 0 12rpx;
			position: relative;
			color: #ffffff;
			display: flex;
		}
		
		.apply-contnet {
			.apply-item {
				padding: 20rpx;
				
				.add-leader-list {
					padding: 10rpx 0;
					
					.leader-circle {
						width: 20rpx;
						height: 20rpx;
						background-color: #D0D0D0;
						border-radius: 50%;
						
						margin-right: 20rpx;
						
						&.circle-line {
							position: relative;
							
							&::before {
								content: "";
								position: absolute;
								width: 2rpx;
								height: 75rpx;
								background-color: #D0D0D0;
								bottom: -75rpx;
								left: 0;
								right: 0;
								margin: 0 auto;
							}
						}
					}
					
					
					.list-content {
						width: 99%;
					}
				}
			
				
				.review-list {
					overflow-y: hidden;
					
					.detail-item {
						height: 60rpx;
						white-space: nowrap;
						width: 1400rpx;
						
						&.title {
							background-color: #DCDCDC;
						}
						
						&.content {
							border-bottom: 2rpx solid #DCDCDC;
						}
						
						.detail-item-child-one {
							width: 8%;
							height: 100%;
							background-color: #DCDCDC;
							
							&.order-number {
								text-align: center;
								display: flex;
								justify-content: center;
								align-items: center;
								background-color: #EAEAEA;
							}
						}
						
						.detail-item-child {
							width: 23%;
							height: 100%;
							text-align: center;
							display: flex;
							justify-content: center;
							align-items: center;
							position: relative;
							
							// 除了最后一个元素的元素增加伪元素
							&:not(:last-child)::after {
								content: "";
								position: absolute;
								right: 0;
								top: 0;
								bottom: 0;
								margin: auto 0;
								width: 2rpx;
								height: 30rpx;
								background-color: #CDCDCD;
							}
							
						}
					}
				}
				
				.add {
					padding: 20rpx 0;
					color: #2045FC;
				}
			}
			
			.pre-box {
				display: flex;
				flex-wrap: wrap;
				
				.pre-item {
					border-radius: 10rpx;
					width: 100rpx;
					height: 100rpx;
					overflow: hidden;
					position: relative;
					margin: 20rpx;
					
					.u-progress {
						position: absolute;
						bottom: 10rpx;
						left: 8rpx;
						right: 8rpx;
						z-index: 9;
						width: auto;
					}
					
					.pre-item-image {
						width: 100rpx;
						height: 100rpx;
					}
					
					.u-delete-icon {
						position: absolute;
						top: 5rpx;
						right: 5rpx;
						z-index: 10;
						background-color: $u-type-error;
						border-radius: 100rpx;
						width: 36rpx;
						height: 36rpx;
						display: flex;
						align-items: center;
						justify-content: center;
					}
				}
			}
		}
		
		.submit-btn {
			margin: 30rpx;
			.submit-btn-content {
				width: 100%;
				padding: 20rpx;
				background-color: #2C48F2;
				border-radius: 50rpx;
			}
		}
		
		.detail-popup {
			padding: 20rpx;
		}
	}
</style>
